package com.whp02.annotation.bd;

/**
 * @author wanghp
 * @version 1.0
 * @description: TODO
 * @date 2020/12/1 16:14
 */

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class XmlSimpleUse {

	public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
		//读取xml文件
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("config/test-xml-read.xml");
		InputStream inputStream = url.openStream();
		//将流转变为InputSource，在后续xml解析使用
		InputSource inputSource = new InputSource(inputStream);
		DocumentBuilderFactory factory = createDocumentBuilderFactory();

		DocumentBuilder docBuilder = factory.newDocumentBuilder();
		// 可选，设置实体解析器，其实就是：你可以自定义去哪里加载xsd/dtd文件
		docBuilder.setEntityResolver(new EntityResolver() {
			@Override
			public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
				return null;
			}
		});
		// 设置回调处理器，当解析出现错误时，（比如xsd里指定了不能出现a元素，然后xml里出现了a元素）
		docBuilder.setErrorHandler(null);
		//解析xml文件，获取到Document，代表了整个文件
		Document document = docBuilder.parse(inputSource);
		// 获取根元素
		Element root = document.getDocumentElement();
		System.out.println(String.format("root is %s", root));

		//获取根元素下的每个child元素
		NodeList nodeList = root.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node instanceof Element) {
				Element ele = (Element) node;
				System.out.println(String.format("ele: %s", ele));
			}
		}
	}

	protected static DocumentBuilderFactory createDocumentBuilderFactory() {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(true);
		// Enforce namespace aware for XSD...
		factory.setNamespaceAware(true);

		return factory;
	}
}

